// pages/details/details.js
const app = getApp()
var url = require('../../utils/url.js');
var goodsId;
var priceIndex = 0;
var token;
var user_id=0;
var formid;
var last_page=1;
var page=1
var shareuSer=0;
var loadMore = function (that) {
  wx.showLoading({
    title: '加载中',
  });
  if (page == 1) {
    page = 2
  }
  if (page < last_page || page == last_page) {
    console.log(page)
    wx.request({
      url: url.URl + 'goods/evaluation',
      data: { goods_id: goodsId, page: page },
      method: 'get',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        console.log(res.data)
        wx.hideLoading();
        that.setData({
          evaluate: that.data.evaluate.concat(res.data.data.data)
        });
        page++;
      }
    });
  } else {
    wx.hideLoading();
    that.setData({
      nodata: 1,
      skill: true
    })
  }
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    banner:[],
    indicatorDots: true,  //小点
    indicatorColor: "white",
    autoplay: true,  //是否自动轮播
    interval: 3000,  //间隔时间
    duration: 500,  //滑动时间
    tabs:["商品详情","视频","用户评价"],
    activeIndex:0,
    image:[],
    goods_body:[],
    thisTimeItem:[],
    ads:"",
    goodsprice:"",
    num:1,
    spec:true,
    specLIst:"",
    totalSpec:"",
    ids:"",
    goodId:"",
    goodsStorage:0,
    selGoods:[],
    muti_spec:"",
    specId:0,
    more:true,
    collect:"",
    formid:"",
    goodsInfo:""
  },
  onLoad: function (options) { 
    var that = this;
    console.log(options)
    wx.getStorage({
      key: 'token',
      success: function (res) {
        token = res.data
        // console.log(res)
      },
    })
    
    if (options.userId){
      wx.setStorage({
        key: 'rec_id',
        data: options.userId,
      })
    }
    wx.getStorage({
      key: 'userinfo',
      success: function (res) {
        console.log(res.data.id)
        user_id = res.data.id
      },fail:function(){
        console.log(111)
      }
    })
    console.log(user_id)
    goodsId = options.goodsId;
    that.getGood()
    that.getEval()
    that.getSpec()
  },
  //tab切换
  tabClick:function(e){
    var that=this;
    var idx = e.currentTarget.dataset.idx;
    var activeIndex = that.data.activeIndex;
    if (idx == activeIndex){
      return false
    }else{
       that.setData({
         activeIndex:idx
       })
    }
  },
  moreL:function(){
    var more=this.data.more;
    
     this.setData({
       more: !more 
     })
  },
  toINDEX:function(){
     wx.switchTab({
       url: '/pages/index/index',
     })
  },
  toCART: function () {
    wx.switchTab({
      url: '/pages/cart/cart',
    })
  },
  //获取商品
  getGood() {
    var that = this;
    wx.showLoading({
      title: '加载中..',
    })
    wx.request({
      url: url.URl + 'goods/info',
      data: { goods_id: goodsId, user_id: user_id},
      method: 'GET',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var msg = res.data.msg;
        if (res.data.code == 200) {
          console.log(res)
          var row=res.data.data.row;
          that.setData({
            ads: res.data.data.ads,
            collect: res.data.data.goods_collect,
            row: row,
            banner: row.goods_images,
            goods_body: row.goods_body,
            goodsprice: row.goods_price,
            muti_spec: row.muti_spec,
            goods_state: row.goods_state,
            goodsthumb: row.goods_thumb,
            goodsStorage: row.goods_storage
          })
          wx.hideLoading()
        } else if (res.data.code == 201) {

        } else {
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  
//获取评价
  getEval() {
    var that = this;
    wx.showLoading({
      title: '加载中..',
    })
    wx.request({
      url: url.URl + 'goods/evaluation',
      data: { goods_id: goodsId,page:page },
      method: 'GET',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var msg = res.data.msg;
        if (res.data.code == 200) {
          console.log(res)
          last_page = res.data.data.last_page
          that.setData({
            evaluate:res.data.data.data
          })
          wx.hideLoading()
        } else if (res.data.code == 201) {

        } else {
          // wx.showToast({
          //   title: msg,
          //   icon: 'none',
          //   duration: 2000
          // })
        }
      }
    })  
  },
  toCollect: function (e, that, formid){
    var that = this;
    token = wx.getStorageSync("token")
    formid = e.detail.formId
    this.setData({
      formid: formid
    })
    var collect = this.data.collect;
    
    if(token){
      wx.request({
        url: url.URl + 'goods/collect',
        data: { goods_id: goodsId, is_collect: collect },
        method: 'post',
        header: {
          'Authorization': token
        },
        success: function (res) {
          var msg = res.data.msg;
          console.log(res)
          wx.hideLoading()
          if (res.data.code == 200) {
            wx.showToast({
              title: msg,
              icon: 'none',
              duration: 2000,
              success:function(){
                that.setData({
                  collect:!collect
                })
              }
            })
            
          }else if(res.data.code==401){
              wx.showModal({
                title: '提示',
                content: '登录过期，请重新登录',
                showCancel: false,
                confirmText: '我知道了',
                confirmColor: '#DD2626',
                success: function(res) {
                  if(res.confirm){
                    wx.getStorage({
                      key: 'rec_id',
                      success: function (res) {
                        shareuSer = res.data
                        app.onGotUserInfo(e, that, formid, shareuSer)
                      },
                      fail: function () {
                        shareuSer = 0
                        app.onGotUserInfo(e, that, formid, shareuSer)
                      }
                    })
                  }
                },
              })
          }else {
            wx.showToast({
              title: msg,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    }else{
      wx.getStorage({
        key: 'rec_id',
        success: function (res) {
          shareuSer = res.data
          app.onGotUserInfo(e, that, formid, shareuSer)
        },
        fail: function () {
          shareuSer = 0
          app.onGotUserInfo(e, that, formid, shareuSer)
        }
      })
    }
  },
  //获取规格
  getSpec(){
    var that = this;
    wx.showLoading({
      title: '加载中..',
    })
    wx.request({
      url: url.URl + 'goods/spec',
      data: { goods_id: goodsId },
      method: 'post',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var msg = res.data.msg;
        if (res.data.code == 200) {
          console.log(res)
          var checked ="checked";
          var specList = res.data.data.spec;
          for (let i = 0; i < specList.length; i++) {
            for (let j = 0; j < specList[i].sub.length; j++) {
              specList[i].sub[j][checked] = false;
            }
          }
          that.setData({
            specLIst: specList,
            totalSpec: res.data.data.spec_goods,
          })
          wx.hideLoading()
        } else if (res.data.code == 201) {

        } else {
          // wx.showToast({
          //   title: msg,
          //   icon: 'none',
          //   duration: 2000
          // })
        }
      }
    })
  },
  bindMinus: function () {
    var num = this.data.num;
    if (num > 1) {
      num--;
    }
    // 将数值与状态写回
    this.setData({
      num: num,
    });
  },
  /* 点击加号 */
  bindPlus: function () {
    var that=this;
    var selGoods = that.data.selGoods;
    var num = this.data.num;
    var goodsStorage = this.data.goodsStorage;
    var limit_num = this.data.limit_num;
    var muti_spec = that.data.muti_spec;
    if (muti_spec == 1&&selGoods.length == 0){
      wx.showToast({
        title: '请选择规格',
        icon: 'none',
      })
    }else{
      if (num < goodsStorage) {
        num++;
        that.setData({
          num: num,
        });
      } else {
        wx.showToast({
          title: '不能再大了',
          icon: 'none',
        })
      }
    }
    
    
    
    // 将数值与状态写回
    
  },
  //图片自适应
  imageLoad: function (e) {
    var $width = e.detail.width,    //获取图片真实宽度
      $height = e.detail.height,
      ratio = $width / $height;    //图片的真实宽高比例
    var viewWidth = 750,           //设置图片显示宽度，左右留有16rpx边距
      viewHeight = 750 / ratio;    //计算的高度值
    var image = this.data.goods_body;
    //将图片的datadata-index作为image对象的key,然后存储图片的宽高值
    image[e.target.dataset.index] = {
      width: viewWidth,
      height: viewHeight
    }
    // console.log(image)
    this.setData({
      image: image
    })
  },
  tanSpec: function (e, that, formid){
    var that=this;
    token = wx.getStorageSync("token")
    console.log(e.detail.formId);
    formid = e.detail.formId
    this.setData({
      formid: formid
    })
    if(token){
      this.setData({
        spec: false
      })
    }else{
      wx.getStorage({
        key: 'rec_id',
        success: function (res) {
          shareuSer = res.data
          app.onGotUserInfo(e, that, formid, shareuSer)
        },
        fail: function () {
          shareuSer = 0
          app.onGotUserInfo(e, that, formid, shareuSer)
        }
      })
    }
     
  },
  close:function(){
    this.setData({
      spec: true
    })
  },
  clickSkuValue: function (event) {
    let that = this;
    let goodsSpecName = event.currentTarget.dataset.value;
    let specValueId = event.currentTarget.dataset.valueId;
    let specValuePid = event.currentTarget.dataset.pid;
    let _attributeList = this.data.specLIst;
    if (_attributeList.length == 0) {
      console.log(1)
    } else {
      for (let i = 0; i < _attributeList.length; i++) {
        if (_attributeList[i].id === specValuePid) {
          for (let j = 0; j < _attributeList[i].sub.length; j++) {
            if (_attributeList[i].sub[j].id == specValueId) {
              //如果已经选中，则反选
              if (_attributeList[i].sub[j].checked) {
                _attributeList[i].sub[j].checked = false;
              } else {
                _attributeList[i].sub[j].checked = true;
              }
            } else {
              _attributeList[i].sub[j].checked = false;
            }
          }
        }
      }
    }
    // console.log(_attributeList)
    this.setData({
      specLIst: _attributeList,
    });
    //重新计算spec改变后的信息
    this.changeSpecInfo();
    this.getNumAndPrice();
    //重新计算哪些值不可以点击,先不做
  },
  isCheckedAllSpec: function () {
    return !this.getCheckedSpecValue().some(function (v) {
      if (v.valueId == 0) {
        return true;
      }
    });
  },
  getCheckedSpecKey: function () {
    let checkedValue = this.getCheckedSpecValue().map(function (v) {
      return v.valueId;
    });

    return checkedValueId;
  },
  getCheckedSpecText: function () {
    let checkedValue = this.getCheckedSpecValue().map(function (v) {
      return v.valueText;
    });

    return checkedValueText;
  },
  getCheckedSpecValue: function () {
    let checkedValues = [];
    let _attributeList = this.data.specLIst;
    if (_attributeList.length == 0) {
      console.log(_attributeList)
    } else {
      for (let i = 0; i < _attributeList.length; i++) {
        let _checkedObj = {
          //name: _attributeList[i].specification,
          name: _attributeList[i].name,
          valueId: 0,
          valueText: '',
          valuePath:''
        };
        for (let j = 0; j < _attributeList[i].sub.length; j++) {
          if (_attributeList[i].sub[j].checked) {
            _checkedObj.valueId = _attributeList[i].sub[j].id;
            _checkedObj.valueText = _attributeList[i].sub[j].name;
            _checkedObj.valuePath = _attributeList[i].sub[j].path;
            //checkedValues.push(_checkedObj);//放在这里，就不用过滤valueId为0的
          }
        }
        checkedValues.push(_checkedObj);
      }
    }
    // console.log(checkedValues)
    return checkedValues;

  },
  changeSpecInfo: function () {

    let checkedNameValue = this.getCheckedSpecValue();

    //设置选择的信息 （获取已选属性的文本数组？）
    let checkedValue = checkedNameValue.filter(function (v) {
      if (v.valueId != 0) {
        return true;
      } else {
        return false;
      }
    }).map(function (v) {
      return v.valueText;
    });
    let checkedValueId = checkedNameValue.filter(function (v) {
      if (v.valueId != 0) {
        return true;
      } else {
        return false;
      }
    }).map(function (v) {
      return v.valueId;
    });
    let checkedPath = checkedNameValue.filter(function (v) {
      if (v.valueId != 0) {
        return true;
      } else {
        return false;
      }
    }).map(function (v) {
      return v.valuePath;
    });
    if (checkedValue.length > 0) {
      this.setData({
        checkedSpecText: checkedValue.join('_'),
        ids: checkedValueId.join('_'),
        goodsSpecName: checkedValue.join('_'),
        checkedSpecPath: checkedPath.join('_')
      });
      console.log(checkedValue.join('_'))
    } else {
      this.setData({
        'checkedSpecText': '请选择规格数量',
      });
    }
  },
  getNumAndPrice: function () {
    // let goodsInfo = [];
    const selcted_id = this.data.selcted_id;
    var checkedSpecText = this.data.checkedSpecText;
    var checkedSpecPath = this.data.checkedSpecPath;
    var ids = this.data.ids;
    var totalSpec = this.data.totalSpec;
    console.log(checkedSpecPath)
    let goodsInfo = totalSpec.filter(function (v) {
      if (v.goods_spec == checkedSpecPath) {
        return true;
      } else {
        return false;
      }
    }).map(function (v) {
      return v;
    });
    console.log(goodsInfo)
    this.setData({
      selGoods: goodsInfo
    })
    if (goodsInfo.length != 0) {
      this.setData({
        goodsStorage: goodsInfo[0].goods_storage,
        goodsprice: goodsInfo[0].goods_price,
        goodId: goodsInfo[0].id,
        goodsthumb: goodsInfo[0].goods_thumb,
        spec_name: goodsInfo[0].spec_name,
        specId: goodsInfo[0].id
      })
    }
    this.setData({
      goodsInfo: goodsInfo,
    })
  },
  //
  /**
   * 生命周期函数--监听页面加载
   */
     
  tobuy:function(){
    var that=this;
    let selGoods = that.data.selGoods;
    let row=that.data.row;
    var specId = that.data.specId;
    var muti_spec = this.data.muti_spec;
     
    console.log(token)
    if (muti_spec==1){
      if (selGoods.length == 0) {
        wx.showToast({
          title: '请选择规格',
          icon: 'none',
        })
      } else {
        var data = {};
        var dataArray = []
        console.log(selGoods)
        // let DoodsId = "goods_id";
        // let SpecId = "spec_goods_id";
        // let goodsNum = "goods_num";
        selGoods[0].goods_name = that.data.row.goods_name;
        selGoods[0].goods_num = that.data.num;
        selGoods[0].spec_goods_id = specId;
        selGoods[0].goods_id = row.id;
        var jsonselGoods = JSON.stringify(selGoods)
        console.log(selGoods)
        wx.navigateTo({
          url: '/pages/ConfirmOrder/ConfirmOrder?goodsInfo=' + jsonselGoods + '&type=1',
        })
      }
    }else{
      var data = {};
      var selGOOds=[];
      var dataArray = []
      console.log(selGoods)
      let goods_id = "goods_id";
      let spec_goods_id = "spec_goods_id";
      let goods_num = "goods_num";
      row.goods_num = that.data.num;
      row.spec_goods_id = 0;
      row.goods_id = row.id;
      selGOOds.push(row)
      var jsonGoods = JSON.stringify(dataArray)
      var jsonselGoods = JSON.stringify(selGOOds)
      console.log(selGoods)
      wx.navigateTo({
        url: '/pages/ConfirmOrder/ConfirmOrder?goodsInfo=' + jsonselGoods + '&type=1',
      })
    }
    
  },
  toCart(){
    var that = this;
    let selGoods = that.data.selGoods;
    var specId = that.data.specId;
    var specId;
    var muti_spec = this.data.muti_spec;
    var token = wx.getStorageSync("token");
    console.log(token)
    if (selGoods.length == 0 && muti_spec==1) {
      wx.showToast({
        title: '请选择规格',
        icon: 'none',
      })
    } else {
      var data = {};
      var dataArray = []
      console.log(selGoods)
      // let DoodsId = "goods_id";
      // let SpecId = "spec_goods_id";
      // let goodsNum = "goods_num";
      data.goods_id = goodsId;
      if (muti_spec==0){
        data.spec_goods_id = 0;
        data.spec_name = 0;
      }else{
        data.spec_goods_id = specId;
        data.spec_name = selGoods[0].spec_name;
      }
      
      data.num = that.data.num;
      // dataArray.push(data)
      var jsonGoods = JSON.stringify(data)
      console.log(jsonGoods)
      wx.request({
        url: url.URl + 'cart/add',
        data:data,
        method: 'POST',
        header: {
          'Authorization': token
        },
        success: function (res) {
          console.log(res)
          var msg = res.data.msg;
          if (res.data.code == 200) {
              
              wx.showToast({
                title: msg,
                icon: 'success',
                duration: 1000,
                mask: true,
                success: function(res) {
                  that.setData({
                    spec: true
                  })
                },
              })
            // setTimeout(() => {
            //   // 模拟请求数据，并渲染
            //   self.onLoad()
            //   // 数据成功后，停止下拉刷新
            //   wx.stopPullDownRefresh();
            // }, 1000);
          } else {
            wx.showToast({
              title: msg,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var that = this;
    var row = that.data.row;
    if (res.from === 'button') {

    }
    return {
      title: row.goods_name,
      path: '/pages/details/details?goodsId=' + row.id + '&userId=' + user_id,
      imageUrl: row.goods_images[0],
      success: function (res) {
        console.log('成功', res)
      }
    }
  }
})